package com.common.baselibrary.mvp;

import android.content.Context;

import com.common.baselibrary.base.BaseActivity;

import java.util.ArrayList;
import java.util.List;


/**
 * MVP Activity 基类
 * Created by xuyougen on 2018/4/11.
 */

public abstract class BaseMvpActivity<V extends BaseView, P extends BasePresenter<V>> extends BaseActivity implements BaseView, MVPLifecycleObservable {

    private P presenter;
    private LoadingDialog loadingDialog;
    private List<MVPLifecycleObserver> lifecycleObservers;

    {
        lifecycleObservers = new ArrayList<>();
    }

    @Override
    protected void beforeSetView() {
        loadingDialog = new LoadingDialog.Builder(this).build();
        loadingDialog.setCancelable(false);
        presenter = createPresenter();
        presenter.attach((V) this);
    }

    @Override
    public void registerMVPLifecycleObserver(MVPLifecycleObserver observer) {
        lifecycleObservers.add(observer);
    }

    protected abstract P createPresenter();

    public P getPresenter() {
        return presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showLoading() {
        showLoading("加载中");
    }

    @Override
    public void showLoading(String text) {
        if (loadingDialog == null) return;
        loadingDialog.setText(text);
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (loadingDialog == null) return;
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onNoNetwork() {
        for (MVPLifecycleObserver observer : lifecycleObservers) {
            observer.onNoNetwork();
        }
    }

    @Override
    public void onTimeout() {
        for (MVPLifecycleObserver observer : lifecycleObservers) {
            observer.onTimeout();
        }
    }

    @Override
    public boolean noDisposeAfterDetach() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            presenter.detach();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
